package com.example.websocket.xml;

import com.example.websocket.xml.bean.CustomCodeModel;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 解析商品和服务税收编码xml文件数据
 * @author David
 *
 */
public class SaxParseTaxCode extends DefaultHandler {

	private List<CustomCodeModel> taxCodes;

	private CustomCodeModel taxCode ;

	private String preTag; // 记录解析上一个几点名称

	private String fatherTag;

	private StringBuffer sb = new StringBuffer();
	
	private Boolean flag = false;
	
	
	public List<CustomCodeModel> getTaxCodes(InputStream xmlStream) {
		SaxParseTaxCode handler = new SaxParseTaxCode();
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser = null;
		try {
			parser = factory.newSAXParser();
			parser.parse(xmlStream, handler);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (xmlStream != null) {
				try {
					xmlStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}	
			}
			if (factory != null) {
				factory = null;
			}
			if (parser != null) {
				parser = null;
			}
		}
		return handler.getTaxCodes();
	}
	
	public List<CustomCodeModel> getTaxCodes() {
		return taxCodes;
	}

	@Override
	public void startDocument() throws SAXException {
		taxCodes = new ArrayList<>();
	}

	@Override
	public void endDocument() throws SAXException {
		super.endDocument();
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		super.startElement(uri, localName, qName, attributes);
		flag = true;
		if ("FENLEI".equals(qName) || "SPXX".equals(qName)){
			fatherTag = qName;
		}
		if (("FENLEI".equals(preTag) || "FENLEI".equals(fatherTag)) && "Row".equals(qName)) {
			taxCode = new CustomCodeModel();
			taxCode = getValues(taxCode, attributes);
		} else if (("SPXX".equals(preTag) ||  "SPXX".equals(fatherTag)) && "Row".equals(qName)) {
			taxCode = new CustomCodeModel();
			taxCode = getValues(taxCode, attributes);
		}
		sb.setLength(0);
		preTag = qName;
	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		super.endElement(uri, localName, qName);
		flag = false;
		if ("Row".equals(qName)) {
			taxCodes.add(taxCode);
		}
		sb.toString();
		preTag = null;
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		if (preTag != null) {
//			String content=new String(ch,start,length);
			String content=new String(ch,start,length);
			sb.append(ch, start, length);
			if ("Row".equals(preTag)) {

			}
		}
	}

	// 生产XML文件
	public void createXMLBySAX(List<CustomCodeModel> tree, List<CustomCodeModel> children, File file) {
		// 创建SAXTransformerFactory对象
		SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
		try {
			// 通过SAXTransformerFactory对象创建TransformerHandler对象
			TransformerHandler handler = factory.newTransformerHandler();
			// 通过Handler创建Transformer对象
			Transformer transformer = handler.getTransformer();
			// 设置Transformer的属性
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//			if (file != null) {
//				file.createNewFile();
//			}
			// 创建Result对象，并将目的XML文件与其关联
			Result result = new StreamResult(file);
			// 将handler与result关联起来
			handler.setResult(result);
			try {
				// 开启文档
				handler.startDocument();
				// 新建节点
				AttributesImpl firstAtts = new AttributesImpl();
				firstAtts.addAttribute("", "", "TYPE", "", "SPBIANMA");
				handler.startElement("", "", "Date", firstAtts);
				AttributesImpl atts = new AttributesImpl();
				handler.startElement("", "", "FENLEI", null);
				for (CustomCodeModel t : tree) {
					atts.clear();
					atts.addAttribute("", "", "OLD_BM", "", t.getOLD_BM() != null ? t.getOLD_BM().toString() : "");
					atts.addAttribute("", "", "OLD_PID", "", t.getOLD_PID() != null ? t.getOLD_PID().toString() : "");
					atts.addAttribute("", "", "MC", "", t.getMC() != null ? t.getMC() : "");
					atts.addAttribute("", "", "PID", "", t.getPID() != null ? t.getPID().toString() : "");
					atts.addAttribute("", "", "BM", "", t.getBM() != null ? t.getBM().toString() : "");
					handler.startElement("", "", "Row", atts);
					handler.endElement("", "", "Row");
				}
				handler.endElement("", "", "FENLEI");
				handler.startElement("", "", "SPXX", null);
				for (CustomCodeModel t : children) {
					atts.clear();
					atts.addAttribute("", "", "OLD_BM", "", t.getOLD_BM() != null ? t.getOLD_BM().toString() : "");
					atts.addAttribute("", "", "OLD_PID", "", t.getOLD_PID() != null ? t.getOLD_PID().toString() : "");
					atts.addAttribute("", "", "MC", "", t.getMC() != null ? t.getMC() : "");
					atts.addAttribute("", "", "PID", "", t.getPID() != null ? t.getPID().toString() : "");
					atts.addAttribute("", "", "BM", "", t.getBM() != null ? t.getBM().toString() : "");
					atts.addAttribute("", "", "GGXH", "", t.getGGXH() != null ? t.getGGXH() : "");
					atts.addAttribute("", "", "SYYHBZ", "", t.getSYYHBZ() != null ? t.getSYYHBZ() : "");
					atts.addAttribute("", "", "SL", "", t.getSL() != null ? t.getSL().toString() : "");
					atts.addAttribute("", "", "SPFLBM", "", t.getSPFLBM() != null ? t.getSPFLBM() : "");
					atts.addAttribute("", "", "JM", "", t.getJM() != null ? t.getJM() : "");
					atts.addAttribute("", "", "HSBZ", "", t.getHSBZ() != null ? t.getHSBZ().toString() : "");
					atts.addAttribute("", "", "YHZC", "", t.getYHZC() != null ? t.getYHZC() : "");
					atts.addAttribute("", "", "JLDW", "", t.getJLDW() != null ? t.getJLDW() : "");
					atts.addAttribute("", "", "DJ", "", t.getDJ() != null ? t.getDJ().toString() : "");
					atts.addAttribute("", "", "SPSM", "", t.getSPSM() != null ? t.getSPSM().toString() : "");
					atts.addAttribute("", "", "SLLX", "", t.getSLLX() != null ? t.getSLLX() : "");
					handler.startElement("", "", "Row", atts);
					handler.endElement("", "", "Row");
				}
				handler.endElement("", "", "SPXX");
				// 关闭节点
				handler.endElement("", "", "Date");
				// 关闭文档
				handler.endDocument();
			} catch (SAXException e) {
				e.printStackTrace();
			}
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		}
	}

	private CustomCodeModel getValues(CustomCodeModel taxCode, Attributes attributes){
		for (int i = 0; i < attributes.getLength(); i++) {
			String localName = attributes.getLocalName(i);
			if (localName == null) {
				continue;
			}
			String value = attributes.getValue(i);
			switch (localName){
				case "GGXH":
					taxCode.setGGXH(value); // 规格
					break;
				case "OLD_BM":
					taxCode.setOLD_BM(Long.valueOf(value)); // 规格
					break;
				case "SYYHBZ":
					taxCode.setSYYHBZ(value); // 规格
					break;
				case "SL":
					taxCode.setSL(Double.valueOf(value)); // 规格
					break;
				case "OLD_PID":
					taxCode.setOLD_PID(Long.valueOf(value)); // 规格
					break;
				case "MC":
					taxCode.setMC(value); // 规格
					break;
				case "PID":
					taxCode.setPID(Long.valueOf(value)); // 规格
					break;
				case "BM":
					taxCode.setBM(Long.valueOf(value)); // 规格
					break;
				case "SPFLBM":
					taxCode.setSPFLBM(value); // 规格
					break;
				case "JM":
					taxCode.setJM(value); // 规格
					break;
				case "HSBZ":
					taxCode.setHSBZ(Integer.valueOf(value)); // 规格
					break;
				case "YHZC":
					taxCode.setYHZC(value); // 规格
					break;
				case "JLDW":
					taxCode.setJLDW(value); // 规格
					break;
				case "DJ":
					taxCode.setDJ(Double.valueOf(value)); // 规格
					break;
				case "SPSM":
					taxCode.setSPSM(Long.valueOf(value)); // 规格
					break;
				case "SLLX":
					taxCode.setSLLX(value); // 规格
					break;
			}
		}
		return taxCode;
	}
	
}
